package com.onewingu.gcs.client;

import java.util.ArrayList;
import java.util.List;

import com.onewingu.gcs.shared.GroupInfo;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class GContactSync implements EntryPoint {
	
	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		final GContactSyncServiceAsync gcssa = (GContactSyncServiceAsync)GWT.create(GContactSyncService.class);

		GroupPanel groupPanel = new GroupPanel();
		final VerticalPanel vp = new VerticalPanel();
		final TextBox tb = new TextBox();
		final PasswordTextBox ptb = new PasswordTextBox();
		final Button submitButton = new Button();
		submitButton.setText("Update Source Account");
		vp.add(tb);
		vp.add(ptb);
		vp.add(submitButton);
		vp.add(groupPanel);
		String saUsername = null;
		
		final AsyncCallback<Void> setSourceAccountCallback = new AsyncCallback<Void>() {
			
			@Override
			public void onSuccess(Void result) {
				vp.add(new Label("source account added"));
				RootPanel.get("groups").add(vp);
			}
			
			@Override
			public void onFailure(Throwable caught) {
				tb.setText("");
				vp.add(new Label(caught.getMessage()));
				RootPanel.get("groups").add(vp);
			}
		};
		
		submitButton.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				gcssa.setSourceAccount(tb.getText(), ptb.getText(), setSourceAccountCallback);
			}
		});
		
		gcssa.getSourceAccount(new AsyncCallback<String>() {
			
			@Override
			public void onSuccess(final String result) {
				if(result != null) {
					tb.setText(result);
					RootPanel.get("groups").add(vp);
					gcssa.getGroups(result, new AsyncCallback<List<GroupInfo>>() {
						
						@Override
						public void onSuccess(List<GroupInfo> results) {
							GroupPanel gp = (GroupPanel)vp.getWidget(3);
							gp.setSaUsername(result);
							gp.setGroups(results);
						}
						
						@Override
						public void onFailure(Throwable caught) {
							RootPanel.get("groups").add(new Label("error: " + caught.getMessage()));
						}
					});
				} else {
					tb.setText("");
					RootPanel.get("groups").add(vp);
				}
			}
			
			@Override
			public void onFailure(Throwable caught) {
				Label label = new Label(caught.getMessage());
				RootPanel.get("groups").add(label);
			}
		});

	}
}
